<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.j_username" :placeholder="$t('login.username')">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.j_password"
        type="password"
        :placeholder="$t('login.password')"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)">{{ $t("login.reset") }}</el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      {{ $t("login.login") }}
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { ElNotification } from "element-plus";
import { loginApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import { getAssignUser } from "@/api/modules/releaseMangement";
import type { ElForm } from "element-plus";
import md5 from "md5";
import { useI18n } from "vue-i18n";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const { t } = useI18n();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  j_username: [{ required: true, message: t("login.rules.usernameRequired"), trigger: "blur" }],
  j_password: [{ required: true, message: t("login.rules.passwordRequired"), trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  username: "admin",
  password: "admin",
  j_loginModel: "token",
  j_tenantId: "",
  _spring_security_remember_me: "on",
  j_username: "",
  j_password: "",
  sso: false
});

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const data = await loginApi({ ...loginForm, password: md5(loginForm.password) });
      const token = JSON.stringify(data).replaceAll(/"/g, "");
      localStorage.setItem("username", loginForm.j_username);
      localStorage.setItem("token", token);
      userStore.setToken(token);
      userStore.setUsername(loginForm.j_username);
      userStore.setMenuFlag("index");
      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);

      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: `${t("login.welcomeMessage")} ${import.meta.env.VITE_GLOB_APP_TITLE}`,
        type: "success",
        duration: 3000
      });
      // 清空部门缓存
      userStore.setDepartmentTree([]);
      if (loginForm.sso) {
        window.location.href = "https://yhgd.gdhwater.com:16443/sso/";
      } else {
        window.location.href = window.location.origin;
      }
    } catch (e) {
      if (loginForm.sso) {
        ElNotification({
          title: getTimeState(),
          message: "登录异常，请重新登录",
          type: "error",
          duration: 3000
        });
        window.location.href =
          "https://iam.gdhwater.com/idp/oauth2/authorize?redirect_uri=https%3A%2F%2Fyhgd.gdhwater.com%3A16443%2Fsso%2Fapi%2Fpages%2ForgSync!syncShuiWuUserReceiveCode.action&state=state&client_id=opsservice&response_type=code";
      } else {
        ElNotification({
          title: getTimeState(),
          message: "账号或密码错误",
          type: "error",
          duration: 3000
        });
      }
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  loginForm.sso = false;
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };

  const searchParams = new URLSearchParams(window.location.search);
  let user = searchParams.get("user");
  let password = searchParams.get("password");
  let sso = searchParams.get("sso");
  let autoLoginusername = searchParams.get("username");
  if (autoLoginusername != null) {
    const params = {
      userName: autoLoginusername
    };
    getAssignUser(params).then(res => {
      if (res != null) {
        console.log(res);
        loginForm.j_username = autoLoginusername as string;
        loginForm.j_password = (res as any).app_password as string;
        login(loginFormRef.value);
      } else {
        ElNotification({
          title: getTimeState(),
          message: "不存在该用户",
          type: "error",
          duration: 3000
        });
      }
    });
  }
  if (sso != null) {
    loginForm.sso = true;
    if (user != null && password != null) {
      console.log(searchParams.get("user"));
      console.log(searchParams.get("password"));
      loginForm.j_username = user;
      loginForm.j_password = password;
      login(loginFormRef.value);
      //window.location.href="http://localhost:8848";
    }
  } else {
    const currentUrl = window.location.href; // 获取当前浏览器的完整 URL

    // 使用 includes() 方法 (推荐，现代浏览器)
    if (currentUrl.includes("sso")) {
      window.location.href =
        "https://iam.gdhwater.com/idp/oauth2/authorize?redirect_uri=https%3A%2F%2Fyhgd.gdhwater.com%3A16443%2Fsso%2Fapi%2Fpages%2ForgSync!syncShuiWuUserReceiveCode.action&state=state&client_id=opsservice&response_type=code";
    }

    // window.location.href="http://localhost:8080/itsm-webapp/pages/orgSync!syncShuiWuUserReceiveCode.action?code=11";
  }

  // if(true)
  //  window.location.href="http://localhost:8080/itsm-webapp/pages/orgSync!syncShuiWuUserReceiveCode.action?code=admin";
  // window.location.href="https://iam-dev.gdhwater.com/idp/oauth2/authorize?redirect_uri=https://www.baidu.com&state=xxxx&client_id=xxxxx&response_type=code";
  // window.location.href="https://iam-dev.gdhwater.com/idp/oauth2/authorize?redirect_uri=http://192.168.0.125:8080/itsm-webapp/pages/orgSync!syncShuiWuUserReceiveCode.action&state=state&client_id=opsservice&response_type=code";
});

onBeforeUnmount(() => {
  document.onkeydown = null;
});
</script>

<style scoped lang="scss">
.login-container {
  height: 100%;
  min-height: 550px;
  background-color: #eeeeee;
  background-image: url("@/assets/images/login_bg.svg");
  background-size: 100% 100%;
  background-size: cover;
  .login-box {
    position: relative;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 96.5%;
    height: 94%;
    padding: 0 50px;
    background-color: rgb(255 255 255 / 80%);
    border-radius: 10px;
    .dark {
      position: absolute;
      top: 13px;
      right: 18px;
    }
    .login-left {
      width: 800px;
      margin-right: 10px;
      .login-left-img {
        width: 100%;
        height: 100%;
      }
    }
    .login-form {
      width: 420px;
      padding: 50px 40px 45px;
      background-color: var(--el-bg-color);
      border-radius: 10px;
      box-shadow: rgb(0 0 0 / 10%) 0 2px 10px 2px;
      .login-logo {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 45px;
        .login-icon {
          width: 60px;
        }
        .logo-text {
          padding: 0 0 0 25px;
          margin: 0;
          font-size: 42px;
          font-weight: bold;
          color: #34495e;
          white-space: nowrap;
        }
      }
      .el-form-item {
        margin-bottom: 40px;
      }
      .login-btn {
        display: flex;
        justify-content: space-between;
        width: 100%;
        margin-top: 40px;
        white-space: nowrap;
        .el-button {
          width: 185px;
        }
      }
    }
  }
}

@media screen and (width <= 1250px) {
  .login-left {
    display: none;
  }
}

@media screen and (width <= 600px) {
  .login-form {
    width: 97% !important;
  }
}
</style>
